<?php
/**
 * kol视频
 * User: bgl
 * Date: 2023/3/14
 * Time: 0:22
 */

namespace App\Admin\Controllers\KolManage;


use App\Admin\Ajax\KolManage\KolVideoAjax;
use App\Admin\Controllers\ErpController;
use App\Models\KolManage\Kol;
use App\Models\KolManage\KolSku;
use App\Models\KolManage\KolVideo;
use App\Util\RExcel;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Illuminate\Http\Request;

class KolVideoController extends ErpController {

    protected $title = 'Kol红人视频';

    protected $filters = [
        'order_no' => null,
        'kol_id' => null,
        'link_type' => null,
        'status' => null,
    ];

    protected function grid()
    {
        $filters = $this->getFilters();
        $this->initFilters($filters);
        $query = $this->_initQuery($filters);
        $paginator = $this->paginator($query);
        $action = $this->getAction();
        $filtersBlade = [];
        $filtersBlade['order_no'] = $this->filters['order_no'];
        $filtersBlade['kol_id'] = getOptions(Kol::options(), $this->filters['kol_id']);
        $filtersBlade['link_type'] = getOptions(KolVideo::$_link_type, $this->filters['link_type']);
        $filtersBlade['status'] = getOptions(KolVideo::$_status, $this->filters['status']);

        $downloadUrl = $this->getDownloadUrl('/xqc/kol-manage/kol-video-download');

        return view('kol-manage.kol-video.list.index', compact('paginator','action','filtersBlade','downloadUrl'));
    }

    private function _initQuery($filters){
        $query = KolVideo::query()->orderBy('id', 'DESC');
        foreach ($filters as $field => $filter){
            if(!$filter)continue;

            if($field == 'order_no'){
                $query->where('order_no',$filter);
            }

            if(in_array($field,['order_no','kol_id','link_type','status'])){
                $query->where($field,$filter);
            }
        }
        return $query;
    }

    public function ajax(){
        $ajax = new KolVideoAjax();
        return $this->callAjax($ajax);
    }

    public function download(){
        $filters = $this->getFilters();
        $query = $this->_initQuery($filters);
        $this->_exeDownload($query);
    }

    private function _exeDownload($query){
        $head = ['订单号','kol红人','链接类型','链接地址','上线时间','点赞数','观看量','评论数','转化数','广告费','汇率','备注','启用'];
        RExcel::exportCsv('kol红人视频', function () use ($head, $query) {
            $fp = fopen('php://output', 'w');
            fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));
            fputcsv($fp, $head);
            $query->chunk(1000, function ($re) use ($fp){
                $data = KolVideo::getDownloadData($re);
                foreach ($data as $item) {
                    fputcsv($fp, $item);
                }
            });
        });
    }

    protected function form(){

        $form = new Form(new KolVideo());

        $form->tools(function (Form\Tools $tools){
            $tools->disableView();
        });

        $form->select('kol_code', 'kol账号')
            ->options(Kol::options())
            ->required()
            ->load('skus','/xqc/api-sys/kol-sku-list')->setWidth(5);;

        //$form->multipleSelect('skus', 'kol产品')
        //    ->options(function (){
        //        $kolId = $this->kol_id ?: old('kol_id');
        //        $obj = KolSku::options(['kol_id' => $kolId]);
        //        if($obj->isNotEmpty()) {
        //            return $obj->toArray();
        //        }else{
        //            return [];
        //        }
        //    })
        //    ->rules("required")->setWidth(5);;

        $form->hidden('id');
        $form->text('order_no', '订单号')->setWidth(5);
        //$form->select('kol_id', 'kol红人')->options(Kol::options())->required()->rules("required")->setWidth(5);
        //$form->multipleSelect('sku', 'kol产品')->options(KolSku::options())->required()->rules("required")->setWidth(5);
        $form->select('link_type', '链接类型')->options(KolVideo::$_link_type)->required()->rules("required")->setWidth(5);
        $form->text('link_url', '链接地址')->setWidth(5);
        $form->datetime('link_online_time', '上线时间')->setWidth(5);

        $form->text('like_num', '点赞数')->setWidth(5);
        $form->text('view_num', '观看量')->setWidth(5);
        $form->text('comment_num', '评论数')->setWidth(5);
        $form->text('convert_num', '转化数')->setWidth(5);
        $form->text('advert_cost', '广告费')->setWidth(5);
        $form->text('exchange_rate', '汇率')->setWidth(5);

        $form->textarea('remark', '备注')->setWidth(5);
        $form->radio('status', '状态')->options(Kol::$_status)->default(1)->setWidth(5);
        $form->hidden('admin_id')->value(Admin::user()->id);

        $form->divider();

        if($form->isCreating()){
            $form->disableCreatingCheck(false);
        }

        $form->saving(function (Form $form) {

            // 判断是否是新增操作
            if ($form->isCreating()) {
                $count = KolVideo::query()
                    ->where('id', '<>', $form->model()->id)
                    ->where('kol_code', $form->kol_code)
                    ->where('order_no', $form->order_no)
                    ->count();
                if($count > 0){
                    admin_error('重复添加', '该订单号已存在');
                    return back()->withInput();
                }
            }else{
                $count = KolVideo::query()
                    ->where('id', '<>', $form->model()->id)
                    ->where('kol_code', $form->kol_code)
                    ->where('order_no', $form->order_no)
                    ->count();
                if($count > 0){
                    admin_error('重复添加', '该订单号已存在');
                    return back()->withInput();
                }
            }
        });

        $form->tools(function (Form\Tools $tools) {
            $tools->disableDelete();
        });
        return $form;
    }

}
